/*
 * @Author: wangtao
 * @Date: 2020-08-20 14:07:42
 * @LastEditors: 汪滔
 * @LastEditTime: 2021-08-11 11:43:09
 * @Description: 司机端首页
 */

import React from 'react';
import { View, StyleSheet, Image, Text, PixelRatio } from 'react-native';
import { empty01, iconLoopGreen, iconLoopRed, iconLoopGray } from '@/images';
import { Button, XMListView, XMEmpty, msg } from '@/common';
import {
  px2dp,
  mainBgColorWhite,
  fontColorGreen,
  fontColorDeepGreen,
  fontColorLightGreen,
  fontColorCoffee,
} from '@/styles';
import api from '@/api';
import HeaderLine from './header-line';
import OrderItem from './order-item';
import DriverScheduling from './driver-scheduling';

const { Submit } = Button;

export default class OrderList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isApplyDis: null, // 是否申请配货  1 申请配货，2 没有申请
      unitOptionsMap: {}, // 单位对象map
      queuePosition: 0, // 当前排队人数
    };
    this.myList = null;
    this.myTimer = null;
    this.dataSource = [];
  }

  componentDidMount() {
    this.initList();
    this.getUnitList();
    this.getSupplyCarDistribution();
    this.getPosition();
  }

  componentWillUnmount() {
    this.myTimer && clearInterval(this.myTimer);
  }

  render() {
    const { unitOptionsMap, isApplyDis } = this.state;
    return (
      <>
        {/* {!!this.dataSource.length && (
          <HeaderLine
            canLeave={canLeave}
            onChangeModal={(obj) => onChangeModal(obj)}
          />
        )} */}
        <XMListView
          ref={(list) => {
            this.myList = list;
          }}
          url='supply-app-api/api/v1/supply/driver/pageDriverWaybill'
          methods='GET'
          params={{ status: 1 }}
          dataPropsName='data.list'
          renderRow={(item, index) => (
            <OrderItem
              detail={item}
              index={index}
              unitOptionsMap={unitOptionsMap}
              onRefresh={() => {
                this._onRefresh();
              }}
            />
          )}
          renderEmpty={() =>
            (isApplyDis === 1
              ? this._renderEmptyScheduling()
              : this._renderEmpty())}
          loadingTilte='正在检查运单'
          onRefresh={() => {
            this._onRefresh();
          }}
        />
      </>
    );
  }

  initList = () => {
    // 如果没有运单需要循环检查
    this.dataSource = this.myList.state.dataSource;
    this.myTimer = setInterval(() => {
      this.dataSource = this.myList.state.dataSource;
      if (!this.dataSource.length) {
        this.myList._init();
        this.confirmDriver();
      } else {
        this.myTimer && clearInterval(this.myTimer);
      }
    }, 50000);
  };

  // 当没有运单的时候，未申请调度
  _renderEmpty = () => {
    const { onChangeModal } = this.props;
    return (
      <View style={styles.emptyWrap}>
        <View style={styles.headerStatus}>
          <Image
            source={iconLoopGreen}
            resizeMode='contain'
            style={styles.loopImg}
          />
          <Text style={styles.headerStatusText}>工作中</Text>
        </View>
        <XMEmpty
          emptyImg={empty01}
          desc='暂无进行中的运单'
          boxStyle={{ marginTop: px2dp(40) }}
        />
        <View style={styles.btnWrap}>
          <Submit
            text='申请配货'
            boxStyle={{
              width: px2dp(590),
              height: px2dp(88),
              borderRadius: px2dp(44),
            }}
            btnStyle={{}}
            btnTextStyle={{
              fontSize: px2dp(32),
            }}
            onClick={() => this.saveSupplyCarDistribution(1)}
          />
          <Submit
            text='请假/修车'
            boxStyle={{
              width: px2dp(590),
              height: px2dp(88),
              borderRadius: px2dp(44),
              marginTop: px2dp(32),
              backgroundColor: mainBgColorWhite,
              borderWidth: 1 / PixelRatio.get(),
              borderColor: fontColorCoffee,
            }}
            btnStyle={{}}
            btnTextStyle={{
              fontSize: px2dp(32),
              color: fontColorCoffee,
            }}
            onClick={() =>
              onChangeModal({ type: 'applyLeaveModelIsShow', val: true })}
          />
        </View>
      </View>
    );
  };

  // 当没有运单的时候，已申请调度
  _renderEmptyScheduling = () => {
    const { onChangeModal } = this.props;
    const { queuePosition } = this.state;
    return (
      <View style={styles.emptyWrap}>
        <View style={styles.headerStatus}>
          <Image
            source={iconLoopGreen}
            resizeMode='contain'
            style={styles.loopImg}
          />
          <Text style={styles.headerStatusText}>工作中</Text>
        </View>
        <DriverScheduling queuePosition={queuePosition} />
        <View style={styles.btnWrap}>
          <Submit
            text='取消配货'
            boxStyle={{
              width: px2dp(590),
              height: px2dp(88),
              borderRadius: px2dp(44),
            }}
            btnStyle={{}}
            btnTextStyle={{
              fontSize: px2dp(32),
            }}
            onClick={() => this.saveSupplyCarDistribution(2)}
          />
          <Submit
            text='请假/修车'
            boxStyle={{
              width: px2dp(590),
              height: px2dp(88),
              borderRadius: px2dp(44),
              marginTop: px2dp(32),
              backgroundColor: mainBgColorWhite,
              borderWidth: 1 / PixelRatio.get(),
              borderColor: fontColorCoffee,
            }}
            btnStyle={{}}
            btnTextStyle={{
              fontSize: px2dp(32),
              color: fontColorCoffee,
            }}
            onClick={() =>
              onChangeModal({ type: 'applyLeaveModelIsShow', val: true })}
          />
        </View>
      </View>
    );
  };

  // 查看 申请配货/撤销配货
  getSupplyCarDistribution = () => {
    api.user.getSupplyCarDistribution().then((res) => {
      if (res.success) {
        this.setState({ isApplyDis: res.data.status });
      } else {
        msg.emit('app:tip', { text: '遇到网络错误，请重试' });
      }
    });
  };

  // 申请配货/撤销配货
  saveSupplyCarDistribution = (status) => {
    api.user.saveSupplyCarDistribution({ status }).then((res) => {
      if (res.success) {
        this.setState({ isApplyDis: status });
        if (status === 1) {
          this.getPosition();
        }
      } else {
        msg.emit('app:tip', { text: res.msg });
      }
    });
  };

  // 获取当前配货排队人数
  getPosition = () => {
    api.supply.getPosition().then((res) => {
      if (res.success) {
        this.setState({ queuePosition: res.data });
      }
    });
  };

  // 获取单位
  getUnitList = () => {
    api.supply.unitList().then((res) => {
      let unitOptionsMap = {};
      res.data.forEach((item) => {
        unitOptionsMap[item.code] = item.name;
      });
      this.setState({ unitOptionsMap });
    });
  };

  // 刷新
  _onRefresh = () => {
    const { initMain } = this.props;
    initMain();
    this.getSupplyCarDistribution();
    this.getPosition();
    this.myList._init();
    this.confirmDriver();
  };

  // 全部确认订单
  confirmDriver = () => {
    api.supply.autoCheckTransports().then((res) => {
      if (res.success) {
        // msg.emit('router: refreshRoute', {
        //   routeName: 'DriverTab',
        // });
      } else {
        msg.emit('app:tip', { text: '遇到网络错误，请重试' });
      }
    });
  };
}

const styles = StyleSheet.create({
  emptyWrap: {
    width: px2dp(702),
    height: px2dp(788),
    backgroundColor: mainBgColorWhite,
    marginHorizontal: px2dp(24),
    marginVertical: px2dp(24),
    borderRadius: px2dp(16),
    paddingHorizontal: px2dp(32),
    paddingVertical: px2dp(32),
  },
  loopImg: {
    width: px2dp(36),
    height: px2dp(36),
  },
  headerStatus: {
    width: px2dp(168),
    height: px2dp(60),
    flexDirection: 'row',
    borderWidth: 1 / PixelRatio.get(),
    borderRadius: px2dp(30),
    borderColor: fontColorDeepGreen,
    backgroundColor: fontColorLightGreen,
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingHorizontal: px2dp(20),
  },
  headerStatusText: {
    fontSize: px2dp(26),
  },
  btnWrap: {
    alignItems: 'center',
    marginTop: px2dp(62),
  },
});
